package sk.tuke.constraintbuilder;
import java.io.File;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.ui.IStartup;

import sk.tuke.constraintbuilder.analyzer.Analyzer;
import sk.tuke.constraintbuilder.analyzer.JavaModelChangeListener;
import sk.tuke.constraintbuilder.analyzer.RulesetRegisterItem;
import sk.tuke.constraintbuilder.analyzer.RulesetManager;
import sk.tuke.constraintbuilder.utils.MyJdtUtils;


public class PluginStartUp implements IStartup {

	@Override
	public void earlyStartup() {		
		//Preferences:
		//autoAnalyzeEnabled (true|false)
		IEclipsePreferences preferences = ConfigurationScope.INSTANCE.getNode("sk.tuke.constraintbuilder");
		
		Boolean autoAnalyzeEnabled = Boolean.valueOf(preferences.get("autoAnalyzeEnabled", "true"));
		
			if(autoAnalyzeEnabled){
				//Add resource change listener
				JavaCore.addElementChangedListener(new JavaModelChangeListener());
				//Initial analyze
				List<RulesetRegisterItem> projectList = RulesetManager.getInstance().getProjectList();
				for (RulesetRegisterItem item : projectList) {
					File schema = new File(item.getSchema());
					if(schema!=null && schema.exists()){
						String projectName = item.getProjectName();
						IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
						if(project!=null){
							try {
								List<IFile> javaFiles = MyJdtUtils.getJavaFilesFromProject(project);
								Analyzer analyzer = new Analyzer(schema);
								for (IFile javaFile : javaFiles) {
									analyzer.examineResource(javaFile);
								}
							} catch (CoreException e) {}
						}
					}
				}
			}
	}

}
